<script setup lang="tsx">
import { reactive, ref } from 'vue'
// import type { TableData } from '@/api/table/types'
import { Descriptions, DescriptionsSchema } from '@/components/Descriptions'
import { onMounted } from 'vue'
// import { departmentMap } from '../../../../public/department'
import { BaseButton } from '@/components/Button'
import { parseXLSX } from './api'
import { reqMissionInfo, downloadResult } from '@/api/bianmafuma'
import type { SingleMissionInfoResponseData } from '@/api/bianmafuma/type'
import { ElTag } from 'element-plus'
import { Table, TableColumn } from '@/components/Table'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'
import { ContentWrap } from '@/components/ContentWrap'
import { inject } from 'vue'

const  departmentMap  = inject<any>('departmentMap')

const $route = useRoute()
const { push, go } = useRouter()

const data = reactive({
  taskName: '/',
  applyTime: '/',
  finishTime: '/',
  taskStatus: 0,
  taskDepartment: '/',
  dataNum: 0,
  mistake: '/'
})

// const id = ref('')

const schema = reactive<DescriptionsSchema[]>([
  {
    field: 'taskName',
    label: '任务名称'
  },
  {
    field: 'taskDepartment',
    label: '数据归属部门',
    slots: {
      default: () => {
        return <span>{data.taskDepartment == '/' ? '/' : departmentMap[data.taskDepartment]}</span>
      }
    }
  },
  {
    field: 'applyTime',
    label: '开始时间',
    slots: {
      default: () => {
        return (
          <span>{data.applyTime == '/' ? '/' : new Date(data.applyTime).toLocaleString('zh-CN', { timeZone: 'UTC' })}</span>
        )
      }
    }
  },
  {
    field: 'finishTime',
    label: '结束时间',
    slots: {
      default: () => {
        return (
          <span>{data.finishTime == '/' ? '/' : new Date(data.finishTime).toLocaleString('zh-CN', { timeZone: 'UTC' })}</span>
        )
      }
    }
  },
  {
    field: 'dataNum',
    label: '数据条数'
  },
  {
    field: 'taskStatus',
    label: '任务状态',
    slots: {
      default: () => {
        const state = taskState(data.taskStatus)
        return (
          <ElTag type={state.type as 'success' | 'danger' | 'warning' | 'info'}>{state.text}</ElTag>
        )
      }
    }
  },
  {
    field: 'resFile',
    label: '结果文件',
    span: 24,
    slots: {
      default: () => {
        if (data.taskStatus == 1)
          return (
            <BaseButton type="success" size="default" onClick={downloadXLSX}>
              下载结果
            </BaseButton>
          )
        else return <span>暂无结果文件</span>
      }
    }
  }
])

const columns: TableColumn[] = [
  {
    field: 'id',
    label: '*实体业务ID',
    width: 100,
    headerAlign: 'center'
  },
  {
    field: 'name',
    label: '*实体名称',
    width: 100,
    headerAlign: 'center'
  },
  {
    field: 'classifyName',
    label: '分类名称',
    width: 100,
    headerAlign: 'center'
  },
  {
    field: 'classifyCode',
    label: '*分类码',
    headerAlign: 'center'
  },
  {
    field: 'regionName',
    label: '所属行政区',
    width: 80,
    headerAlign: 'center'
  },
  {
    field: 'regionCode',
    label: '*行政区划码',
    width: 80,
    headerAlign: 'center'
  },
  {
    field: 'des',
    label: '区域范围说明'
  },
  {
    field: 'lon',
    label: '*经度',
    width: 100,
    headerAlign: 'center'
  },
  {
    field: 'lat',
    label: '*纬度',
    width: 100,
    headerAlign: 'center'
  },
  {
    field: 'alt',
    label: '高程',
    headerAlign: 'center'
  },
  {
    field: 'addition',
    label: '备注',
    headerAlign: 'center'
  },
  {
    field: 'code',
    label: '统一识别代码',
    width: 100,
    headerAlign: 'center'
  },
  {
    field: 'beidou_2d',
    label: '北斗二维网格码',
    width: 100,
    headerAlign: 'center'
  },
  {
    field: 'beidou_3d',
    label: '北斗三维网格码',
    width: 100,
    headerAlign: 'center'
  }
]

// 如果申请已完成，则存储结果文件
let excel: Blob

// 预览表格
const previewTableData = ref([])

const taskState = (state: number) => {
  switch (state) {
    case 0:
      return {
        text: '进行中',
        type: 'primary'
      }
      break
    case 1:
      return {
        text: '已完成',
        type: 'success'
      }
      break
    case 2:
      return {
        text: '错误',
        type: 'danger'
      }
    default:
      return {
        text: '进行中',
        type: 'primary'
      }
  }
}
const downloadXLSX = () => {
  const downloadUrl = window.URL.createObjectURL(
    new Blob([excel!], { type: 'application/vnd.ms-excel' })
  )
  // if (downloadUrl.includes('http:')) {
  //     downloadUrl = downloadUrl.replace('http:', 'https:');
  // }
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = downloadUrl
  a.download = '编码赋码结果.xlsx'
  const event = new MouseEvent('click')
  a.dispatchEvent(event)
}

// 获取申请详情的数据
const getMissionInfo = async () => {
  const res: SingleMissionInfoResponseData = await reqMissionInfo($route.query.id as string)
  data.taskName = res.data?.taskName
  data.applyTime = res.data?.applyTime
  data.taskDepartment = res.data?.taskDepartment
  data.dataNum = res.data?.dataNum
  data.taskStatus = res.data?.taskStatus
  data.finishTime = res.data?.finishTime ?? '/'
  data.mistake = res.data?.mistake ?? '/'

  data.mistake !== '/'
    ? schema.push({
        field: 'mistake',
        label: '报错信息',
        span: 24
      })
    : ''

  if (res.code === 200) {
    if (res.data?.taskStatus == 1) {
      downloadResult($route.query.id as string).then((res) => {
        excel = res

        parseXLSX(new Blob([excel], { type: 'application/vnd.ms-excel' })).then((data) => {
          ;(data as Array<any>)!.shift()

          data = (data as Array<any>).slice(0, 10)
          data = (data as Array<any>).map((item: any) => {
            return {
              id: item[0] || '',
              name: item[1] || '',
              classifyName: item[2] || '',
              classifyCode: item[3] || '',
              regionName: item[4] || '',
              regionCode: item[5] || '',
              des: item[6] || '',
              lon: item[7] || '',
              lat: item[8] || '',
              alt: item[9] || '',
              addition: item[10] || '',
              code: item[11] || '',
              beidou_2d: item[12] || '',
              beidou_3d: item[13] || ''
            }
          })
          previewTableData.value = data as any
        })
      })
    }
  }
}

onMounted(() => {
  getMissionInfo()
})
</script>

<template>
  <!-- title去掉了整个头都没了 -->
  <ContentWrap title=" " @back="push('/encoding/encoding-application')">
    <template #header>
      <BaseButton @click="go(-1)"> 返回 </BaseButton>
    </template>
    <Descriptions :schema="schema" :data="data" />
    <Table
      :columns="columns"
      :data="previewTableData"
      height="350"
      style="margin-left: 1%; width: 98%"
    />
  </ContentWrap>
</template>
